function BCAshowEmsg (msg) {
    var div = document.getElementById("bca_emsg");
    if (div) {
        div.innerHTML = msg;
        div.style.display = "block";
    }
}

function BCAhideEmsg () {
    var div = document.getElementById("bca_emsg");
    if (div)
        div.innerHTML = ".";
    //div.style.display = "none";
}

function BCAinstallEmsg () {
    var div = document.getElementById("emsg");
    var newDiv = div.cloneNode (false);
    newDiv.id = "bca_emsg"
    newDiv.setAttribute ("style", "display:block;text-align:center");
    newDiv.innerHTML = ".";
    div.parentNode.insertBefore (newDiv, div);
    BCAhideEmsg();
}

function BCAgetArmor () {
    var el = document.getElementById ("spanShipArmor");
    if (el) {
        return Number (el.textContent);
    }
    return -1;
}

function BCAgetArmorMax () {
    var el = document.getElementById ("spanShipArmorMax");
    if (el) {
        return Number (el.textContent);
    }
    return -1;
}

function BCAgetResourceById (resId) {
    var resName = "tdCargoRes" + resId;
    var resTd = document.getElementById (resName);
    if (!resTd) return -1;
    
    var amount = resTd.textContent.split(":")[1].split(" ")[0];
    return Number (amount);
}

function BCAgetBotsToTake () {
    var avail = BCAgetResourceById ("8");
    if (avail<1) return 0;
    
    var totake = POgetBotsToRepair (Number(localStorage.getItem("po_bca_armor_strength")), BCAgetArmor (), BCAgetArmorMax ());
    if (totake > avail) return avail;
    return totake;
}

function BCAgetDrugsToTake () {
    var avail = BCAgetResourceById ("51");
    if (avail<1) return 0;
    var defAmount = localStorage.getItem ('po_bca_default_drugs');
    return defAmount>avail?avail:defAmount;
}

function BCAinstallRetreatPath () {
    // Add the control panel for sighting reporting.
    var status = document.getElementById ("commands");
    if (!status) return;

    // Check if the stuff is already installed. If so, delete it first
    var tr = document.getElementById ("po_bca_retreat_path");
    if (tr) tr.parentNode.removeChild (tr);

    // Check if the retreat path is set
    var value = "";
    var rp = localStorage.getItem ("po_bca_retreat_path");
    var botsToTake = BCAgetBotsToTake ();
    var drugsToTake = BCAgetDrugsToTake ();
    var botsCargo = BCAgetResourceById ("8");
    if (!rp && !botsToTake && !drugsToTake && botsCargo >= 10) return;

    // Create a new row in the Status table and insert it
    tr = document.createElement ("tr");
    tr.id = "po_bca_retreat_path";
    status.firstChild.insertBefore (tr, status.firstChild.lastChild);
    td = status.firstChild.childNodes[1].firstChild.cloneNode(false);
    tr.appendChild (td);
    
    if (rp) {
        var reachable = BCAcheckRPreachable (rp);
        value += "<br>"+rp;
        if (!reachable) {
            value += "<span style='color:red;' title='Retreat point out of reach'>! ! !</span>"
        } 
    }
    if (botsToTake) value += "<br><span style='margin: 0pt 18px;'><a id='bca_bots_to_take' style='color:lime;' href='javascript:BCAtakeBots("+botsToTake+");void(0);'>4 - use "+botsToTake+" bots</a></span>";
    if (botsCargo < 10) {
        if (botsCargo < 1) BCAshowEmsg ("<span style='color:red;font-weight:bold'>>>>  Out of bots !!!  <<<</span>");
        else BCAshowEmsg ("<span style='color:yellow;font-weight:bold'>>>>  Low on bots !!!  <<<</span>");
    } else BCAhideEmsg ();
    if (drugsToTake) value += "<br><span style='margin: 0pt 18px;'><a id='bca_drugs_to_take' style='color:lime;' href='javascript:BCAtakeDrugs("+drugsToTake+");void(0);'>5 - use "+drugsToTake+" drugs</a></span>";
    
    td.innerHTML = value;
    if (td.firstChild && td.firstChild.tagName.toLowerCase() == "br")
        td.removeChild (td.firstChild);
}

function BCAcheckRPreachable (rp) {
    var userloc = rp.split ("userloc='")[1].split("'")[0];
    //var tileid = "tileID"+userloc;
    //
    //var transition = false;
    //if (window.ajax == true && window.nav.style.display == "none")
    //    transition = true;
    //
    //if (!transition) {
    //    return (document.getElementById(tileid) != null);
    //}
    // var links = window.navTransition.getElementsByTagName ("a");
    
    var links = null;
    var oncl = null;
    if (window.ajax) {
        if (window.nav.style.display == "none") {
            links = window.navTransition.getElementsByTagName ("a");
        } else {
            links = window.nav.getElementsByTagName ("a");
        }
        oncl = "navAjax("+userloc+")";
    } else {
        links = document.getElementById("navarea").getElementsByTagName ("a");
        oncl = "nav("+userloc+")";
    }
    
    for (var i=0; i<links.length; i++) {
        if (links[i].getAttribute("onclick") == oncl) return true;
    }
    return false;
}

function BCAinnerSB () {
    var links = document.links;
    for (var i=0; i<links.length; i++) {
        if (links[i].textContent == "Exit inner starbase") return true;
    }
    return false;
}

function BCAtrackLastTile () {
    var loc = window.userloc;
    localStorage.setItem ("po_bca_last_tile", localStorage.getItem ("po_bca_current_tile"));
    localStorage.setItem ("po_bca_current_tile", loc);
}


// Register functions to be called by Pardus after PrtialRefresh is done.
addUserFunction (BCAinstallRetreatPath);
addUserFunction (BCAtrackLastTile);

//window.addEventListener ("load", function () {
    BCAinstallEmsg ();
    BCAinstallRetreatPath ();
    BCAtrackLastTile ();
//}, false);

// //////////////////////////////////////////////////////////
// Hotkeys
// //////////////////////////////////////////////////////////
document.addEventListener("keydown",BCAkeyboardAction,true);
function BCAkeyboardAction (e) {
    if(window.name == '' || e.ctrlKey) return;
    if (e.target.nodeName.toUpperCase() == 'INPUT' || e.target.nodeName.toUpperCase() == 'TEXTAREA') return;
    var key = e.keyCode;

//if (key != 16) {
//    alert ("Which:"+e.which+" KeyCode:"+e.keyCode+" Key:"+String.fromCharCode(e.which));
//}

    if (key == 51) BCAfightFirst (); //3
    else if (key == 49) BCAretreat (true); //1
    else if (key == 50) BCArefreshScreen (); //2
    else if (key == 52) BCAtakeBots (-1); //4
    else if (key == 53) BCAtakeDrugs (-1); //5
    else if (key == 48) BCAsetRetreat (); //0
    else if (key == 69) BCAgetShipStats (); //e
    else if (key == 75) BCAcloak (); //k
    else if (key == 76) BCAambush (); //l (L)
    else if (key == 82) BCArepair (); //r
    else if (key == 65) BCAwinFight (e.altKey); //a
    else if (key == 68) BCAwinRetreat (); //d
    else if (key == 67) BCAflyClose (); //c
}

function BCAflyClose () {
    window.location = "main.php?entersb=1";
}

function BCAwinRetreat () {
    var retr = BCAretreat (false);
    var norp = "";
    if (retr == -2) {
        // No retreat point set
        norp = "<span style='color:red;font-weight:bold'>>>>  No retreat point set!!!  Use 0 (zero) key to set RP.<<<</span>";
        BCAshowEmsg (norp);
        norp += "<br>";
    } else if (retr == -3) {
        norp = "<span style='color:red;font-weight:bold'>>>>  RP Out of reach !!!<<<</span>";
        BCAshowEmsg (norp);
        norp += "<br>";
    }
    if (retr < 0) {
        // Already on retreat point or no retreat point set
        var avail = BCAgetResourceById ("8");
        var bots = BCAgetBotsToTake ();
        var minArmor = localStorage.getItem ("po_bca_min_armor");
        if (minArmor) minArmor = Number (minArmor);
        else minArmor = 0;
        var armor = BCAgetArmor ();
        var armorMax = BCAgetArmorMax ();
        
        if (bots > 0) {
            // There's armor damage and we have bots in cargo. Let's repair.
            BCAtakeBots (bots);
            if (avail - bots == 0) {
                BCAshowEmsg (norp+"<span style='color:red;font-weight:bold'>>>>  Ship repaired but you're Out of bots now!!!  <<<</span>");
            } else if (avail - bots < 10) {
                BCAshowEmsg (norp+"<span style='color:red;font-weight:bold'>>>>  Ship fylly repaired but you're Low on bots now ("+avail-bots+")!!!  <<<</span>");
            } else {
                BCAshowEmsg (norp+"<span style='color:lime;font-weight:bold'>>>>  Ship fully repaired  <<<</span>");
            }
            return;
        }
        if (bots < 1 && armor < armorMax) {
            if (armor < minArmor) {
                BCAshowEmsg (norp+"<span style='color:red;font-weight:bold'>>>>  Low armor and no bots to repair !!!  Get some bots!!!  <<<</span>");
            } else {
                BCAshowEmsg (norp+"<span style='color:yellow;font-weight:bold'>>>>  Armor damaged and no bots to repair !!! <<<</span>");
            }
        }
        BCArefreshScreen ();
    }
}

function BCAwinFight (forceFight) {
    var avail = BCAgetResourceById ("8");
    var bots = BCAgetBotsToTake ();
    var minArmor = localStorage.getItem ("po_bca_min_armor");
    if (minArmor) minArmor = Number (minArmor);
    else minArmor = 0;
    var armor = BCAgetArmor ();
    var armorMax = BCAgetArmorMax ();
    
    BCAhideEmsg ();
    //BCAshowEmsg ("<span style='color:lime;font-weight:bold'>>>>  Test  <<<</span>");
    
    if (bots > 0) {
        // There's armor damage and we have bots in cargo. Let's repair.
        BCAtakeBots (bots);
        if (avail - bots == 0) {
            BCAshowEmsg ("<span style='color:red;font-weight:bold'>>>>  Ship repaired but you're Out of bots now!!!  <<<</span>");
        } else if (avail - bots < 10) {
            BCAshowEmsg ("<span style='color:red;font-weight:bold'>>>>  Ship fully repaired but you're Low on bots now ("+avail-bots+")!!!  <<<</span>");
        } else {
            BCAshowEmsg ("<span style='color:lime;font-weight:bold'>>>>  Ship fully repaired  <<<</span>");
        }
        return;
    }
    if (bots < 1 && armor < armorMax) {
        // We've got armor damage but no robots to repair
        if (armor < minArmor) {
            // We can't repair and current armor is below the set minimum level
            if (forceFight) {
                // ALT pressed so we attack anyway.
                BCAfightFirst ();
            } else {
                // No ALT pressed so we just inform the pilot.
                BCAshowEmsg ("<span style='color:red;font-weight:bold'>>>>  Low armor and no bots to repair !!!  Use ALT+A to attack anyway.  <<<</span>");
            }
            return;
        } else {
            // We can't repair but the current armor is above the minimum armor level. Let's attack.
            BCAfightFirst ();
            return;
        }
    }
    
    // No armor damage, let's fight
    BCAfightFirst ();
}

function BCArepair () {
    window.location = "ship_equipment.php";
}

function BCAambush () {
    window.location = "ambush.php";
}

function BCAcloak () {
    if (POisPartialRefresh()) {
        window.cloak (0);
    } else {
        document.getElementById("cloakForm").submit();
    }
}

function BCAsetRetreat () {
    //if (BCAinnerSB()) return;
    var div = document.createElement ("div");
    var loc = POgetLocation ();
    var userloc = window.userloc;
    var value = "<span style='color:lime;font-weight:bold;margin: 0pt 18px;'><a style='color:red;' href='javascript:BCAresetRP();void(0);'>X</a> RP: <a style='color:lime;' userloc='"+userloc+"' href='javascript:BCAretreat();void(0);'>"+loc+"</a></span>";
    localStorage.setItem ("po_bca_retreat_path", value);
    BCAinstallRetreatPath ();
    BCAshowEmsg ("<span style='color:lime;font-weight:bold'>>>>  Retreat point set.  <<<</span>");
}

function BCAfightFirst () {
    if (POisPartialRefresh()) {
        var ops = window.shipsTab;
    } else {
        var ops = document.getElementById ("otherships_content");
    }
    var otherShips = ops.childNodes;
    if (otherShips.length == 0) {
        window.location = "main.php";
        return;
    }
    var pilot = null;
    for (var i=0; i<otherShips.length; i++) {
        var os = otherShips[i];
        var ff = Number (os.getAttribute ("po_ffm_ff"));
        if (ff > 0) continue;
        if (os.getAttribute("bca_attackable") == "false") continue;
        pilot = os;
        break;
    }
    if (pilot) {
        var id = pilot.getAttribute ("po_ffm_id");
        window.location = "ship2ship_combat.php?playerid="+id;
    } else BCArefreshScreen();
}

function BCAresetRP() {
    localStorage.removeItem ("po_bca_retreat_path");
    BCAinstallRetreatPath ();
}

function BCAretreat (lastTile) {
    var inner = BCAinnerSB ();
    //if (BCAinnerSB ()) {
    //    window.location = "main.php?exitsb=1";
    //    return 0;
    //}
    
    // Check if the retreat path is set
    value = localStorage.getItem ("po_bca_retreat_path");
    if (!value || value.length == 0) {
        if (inner) {
            window.location = "main.php?exitsb=1";
            return -2;
        }
        if (lastTile)
            var loc = localStorage.getItem ("po_bca_last_tile");
        else
            return -2;    // No RP set
    } else {
        var reach = BCAcheckRPreachable (value);
        if (!reach) {
            BCAshowEmsg ("<span style='color:red;font-weight:bold'>>>>  RP Out of reach !!!<<<</span>");
            return -3;
        }
        var div = document.createElement ("div");
        div.innerHTML = value;
        var loc = div.firstChild.lastChild.getAttribute ("userloc");
    }
    // Jump to the location
    if (loc) {
        var userloc = String(window.userloc);
        if (userloc == loc) return -1;
        if (window.navAjax) {
            window.navAjax (loc);
            //window.nav (loc);
        } else {
            window.nav (loc);
        }
    } else {
        // No RP set
        return -2;
    }
    
    return 0;
}

function BCArefreshScreen () {
    window.location = "main.php";
}

function BCAtakeBots (amount) {
    if (amount == -1) {
        var elem = document.getElementById ("bca_bots_to_take");
        if (elem) elem.click ();
        return;
    }
    POuseResource (8, amount, BCArefreshScreen);
}

function BCAtakeDrugs (amount) {
    if (amount == -1) {
        var elem = document.getElementById ("bca_drugs_to_take");
        if (elem) elem.click ();
        return;
    }
    POuseResource (51, amount, BCArefreshScreen);
}

function BCAgetShipStats () {
    if (POisPartialRefresh()) {
        var ops = window.shipsTab;
    } else {
        var ops = document.getElementById ("otherships_content");
    }
    var otherShips = ops.childNodes;

    for (var i=0; i<otherShips.length; i++) {
        var processed = otherShips[i].getAttribute ("bca_processed");
        if (processed == "true") continue;
        var id = otherShips[i].getAttribute ("po_ffm_id");
        POgetOtherShipInfo (id, BCAshowShipStats);
        break;
    }
}

function BCAshowShipStats (status, pilotID, ship, hull, armor, shield) {
    if (POisPartialRefresh()) {
        var ops = window.shipsTab;
    } else {
        var ops = document.getElementById ("otherships_content");
    }
    var otherShips = ops.childNodes;

    var pilot = null;
    for (var i=0; i<otherShips.length; i++) {
        var id = otherShips[i].getAttribute ("po_ffm_id");
        if (id != pilotID) continue;
        pilot = otherShips[i];
        break;
    }

    if (!pilot) return;
    pilot.setAttribute ("bca_processed", "true");
    var str;
    if (!status) {
        str = "<span style='color:lime;font-size:10px;font-weight:bold'>Can't be attacked</span>";
        pilot.setAttribute ("bca_attackable", "false");
    } else {
        str = "<span style='color:red;font-size:10px;font-weight:bold'>H:"+hull+"&nbsp;A:"+armor+"&nbsp;S:"+shield+"</span>";
        pilot.setAttribute ("bca_attackable", "true");
    }
    pilot.firstChild.firstChild.lastChild.appendChild (document.createElement("br"));
    var div = document.createElement ("div");
    div.innerHTML = str;
    pilot.firstChild.firstChild.lastChild.appendChild (div.firstChild);
}

// //////////////////////////////////////////////////////////
// End: Hotkeys
// //////////////////////////////////////////////////////////